package com.kyle.controller;

import com.google.gson.Gson;
import com.kyle.base.BaseInfoProperties;
import com.kyle.grace.result.GraceJSONResult;
import com.kyle.grace.result.ResponseStatusEnum;
import com.kyle.pojo.Users;
import com.kyle.pojo.bo.RegistLoginBo;
import com.kyle.pojo.vo.UsersVO;
import com.kyle.service.UsersService;
import com.kyle.utils.IPUtil;
import com.kyle.utils.JWTUtils;
import com.kyle.utils.SMSUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.UUID;

/**
 * @Author：kyle_fu
 * @description: TODO
 * @Date：2024/1/21 15:32
 * @version: 1.0
 */
@RestController
@RequestMapping(value = "passport")
@Slf4j
public class PassPortController extends BaseInfoProperties {


    @Autowired
    private UsersService usersService;
    @Autowired
    private JWTUtils jwtUtils;

    @PostMapping(value = "/getSMSCode")
    public GraceJSONResult getSMSCode(String mobile,
                                      HttpServletRequest request) {
        if (mobile == null || mobile.length() != 11) {
            return GraceJSONResult.errorMsg("手机号不正确或为空,请检查~");
        }

        // 获得用户的ip
        String ip = IPUtil.getRequestIp(request);
        // 限制用户只能在60s内获得一次验证码 根据用户ip去做限制
        redis.setnx60s(MOBILE_SMSCODE + ":" + ip, mobile);

        String code = String.valueOf((int) ((Math.random() * 9 + 1) * 100000));
        //smsUtils.sendSMS(mobile,code);
        log.info("验证码为=======: " + code);
        //把验证码存入redis,用于后续的登录校验
        redis.set(MOBILE_SMSCODE + ":" + mobile, code, 30 * 60);
        return GraceJSONResult.ok();
    }


    @PostMapping(value = "/login")
    public GraceJSONResult getSMSCode(@Valid @RequestBody RegistLoginBo registLoginBo
    ) {

        String mobile = registLoginBo.getMobile();
        String smsCode = registLoginBo.getSmsCode();

        // 1. 从redis中获取验证码用于校验是否正确
        String redisCode = redis.get(MOBILE_SMSCODE + ":" + mobile);
        if (StringUtils.isBlank(redisCode) || !redisCode.equalsIgnoreCase(smsCode)) {
            return GraceJSONResult.errorCustom(ResponseStatusEnum.SMS_CODE_ERROR);
        }
        // 2. 根据mobile查询数据库,判断用户是否存在
        Users users = usersService.queryMobileIsExist(mobile);
        if (users == null) {
            //2.1 如果用户不存在,则表示该用户没有注册过,需要先注册
            users = usersService.createUser(mobile);

        }

        // 3.保存用户token,分布式会话到redis中
//        String uToken = TOKEN_USER_PREFIX + SYMBOL_DOT + UUID.randomUUID();
//        redis.set(REDIS_USER_TOKEN + ":" + users.getId(), uToken);
        String jwt = jwtUtils.createJWTWithPrefix(new Gson().toJson(users),Long.valueOf(1000),TOKEN_USER_PREFIX);
        // 4.用户登录注册后,删除redis中的短信验证码
        redis.del(MOBILE_SMSCODE + ":" + mobile);

        // 5.返回用户信息给前端
        UsersVO usersVO = new UsersVO();
        BeanUtils.copyProperties(users, usersVO);
        usersVO.setUserToken(jwt);

        return GraceJSONResult.ok(usersVO);
    }

    @PostMapping("logout")
    public GraceJSONResult logout(@RequestParam String userId
    ) {

        // 后端只需要清除用户的token信息即可，前端也需要清除相关的用户信息
        redis.del(REDIS_USER_TOKEN + ":" + userId);

        return GraceJSONResult.ok();
    }
}
